import Vue from 'vue'
import Vuex from 'vuex'
import createSisted from 'vuex-persistedstate'

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createSisted()],
  state: {
    cart: [],
    token: ''
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    clearToken(state) {
      state.token = ''
    },
    addCart(state, obj) {
      state.cart.push(obj)
    },
    cutCart(state) {
      state.cart.splice(1)
    },
    addNum(state, obj) {
      state.cart[obj.index].number += obj.number
    },
    addCartNum(state, index) {
      state.cart[index].number++
    },
    cutNum(state, index) {
      state.cart[index].number--
    },
    delOne(state, index) {
      state.cart.splice(index, 1)
    },
    all(state) {
      state.cart.forEach((item) => {
        item.flag = true
      })
    },
    no(state) {
      state.cart.forEach((item) => {
        item.flag = false
      })
    },
    single(state, obj) {
      state.cart[obj.index].flag = obj.flag
    },
  },
  getters: {
    sum(state) {
      var sum = 0
      state.cart.forEach((item) => {
        sum += item.number
      })
      return sum
    },
    count(state) {
      var count = 0;
      state.cart.forEach((item) => {
        if (item.flag) {
          count += item.number * item.price
        }
      })
      return count;
    },
    chan(state) {
      var arr = state.cart.filter((item) => {
        return item.flag
      })
      if (arr.length == state.cart.length) {
        return true
      } else {
        return false
      }
    },
    noflag(state) {
      var arr = state.cart.filter((item) => {
        return !item.flag
      })
      return arr.length
    },
  }
})